package com.starling.control.file
{
	import com.starling.utils.TextureUtil;
	
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;
	import flash.system.System;

	public class FileDIR extends FileBase
	{
		private var _loadIndex:int;
		private var _fileChilds:Vector.<File>;
		
		public function FileDIR(path:String=null)
		{
			super(path);
		}
		
		
		/**
		 * 加载 
		 * 
		 */	
		override public function loadFile(callback:Function):void
		{
			super.loadFile(callback);
			
			dispose();
			fileItems = new Array();
			_loadIndex = 0;
			this._fileSize = 0;
			_fileChilds = new Vector.<File>;
			var arr:Array = this.getDirectoryListing();
			for (var i:int=0;i<arr.length;i++)
			{
				if(arr[i].isDirectory==false)
				{
					if(arr[i].extension.toLocaleLowerCase()=="png"
						|| arr[i].extension.toLocaleLowerCase()=="jpg")
					{
						this._fileSize += arr[i].size;
						_fileChilds.push(arr[i]);
					}
				}
			}
			
			loadHandler();
		}
		
		
		
		/**
		 * 加载处理 
		 * 
		 */		
		private function loadHandler():void
		{
			if(_loadIndex>=_fileChilds.length)
			{
				this._fileNum = _fileChilds.length;
				this._callback();
				return;
			}
			
			var loaderContext:LoaderContext = new LoaderContext(); 
			loaderContext.allowLoadBytesCodeExecution = true; 
			
			var loader:Loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE ,loadComplete);
			
			var textureName:String = decodeURI(_fileChilds[_loadIndex].name);
			textureName = textureName.substring(0 ,textureName.lastIndexOf("."));
			
			fileItems.push({display:loader ,textureName:textureName ,textureType:TextureUtil.TYPE_IMAGE});
			
			loader.load(new URLRequest(_fileChilds[_loadIndex].nativePath) ,loaderContext);
			_loadIndex++;
		}
		
		
		/**
		 * 加载完成 
		 * 
		 */
		private function loadComplete(event:Event):void
		{
			loadHandler();
		}
		
		
		
		/**
		 * 回收 
		 * 
		 */		
		override public function dispose():void
		{
			if(fileItems!=null)
			{
				for (var i:int=0;i<fileItems.length;i++)
				{
					var loader:Loader = fileItems[i].display;
					loader.contentLoaderInfo.removeEventListener(Event.COMPLETE ,loadComplete);
					loader.unloadAndStop();
					loader = null;
				}
				
				fileItems = null;
			}
			
			System.gc();
		}
	}
}